import sys
import os

from PyQt5.QtGui import *  # UI 界面相关
from PyQt5.QtCore import *  # 核心组件包
from PyQt5.QtWidgets import *  # UI 布局相关模块

from qdarkstyle import load_stylesheet_pyqt5
from win10toast import ToastNotifier  # 导入系统通知对象
import time  # 系统时间模块
import datetime
from threading import Timer  # 定时器


class WinNotify(QWidget):
    def __init__(self):
        super(WinNotify, self).__init__()
        self.init_ui()
        self.createTrayIcon()
        # 让托盘图标显示在系统托盘上
        self.trayIcon.show()

    def init_ui(self):
        self.setWindowTitle('windows通知管理器')
        self.setWindowIcon(QIcon('uuus.ico'))
        self.setFixedWidth(800)

        self.notify_subject_label = QLabel()
        self.notify_subject_label.setText('通知主题')

        self.notify_subject_text = QLineEdit()
        # self.notify_subject_text.setPlaceholderText('输入通知主题')
        self.notify_subject_text.setText('倒计时间到了')

        self.notify_current_label = QLabel()
        self.notify_current_label.setText('通知内容')

        self.notify_current_text = QLineEdit()
        # self.notify_current_text.setPlaceholderText('输入通知内容')
        self.notify_current_text.setText("为了身体健康，快去休息吧~")

        self.notify_time_label = QLabel()
        self.notify_time_label.setText('通知间隔')

        self.notify_time_combox = QComboBox()
        self.notify_time_combox.addItems(["5|秒钟", "5|分钟" ,'10|分钟', '30|分钟', '45|分钟', '60|分钟', '120|分钟'])

        self.notify_icon_path = QLineEdit()
        self.notify_icon_path.setPlaceholderText('通知图标(*.ico)')

        self.notify_icon_btn = QPushButton()
        self.notify_icon_btn.setText('选择图标')
        self.notify_icon_btn.clicked.connect(self.notify_icon_btn_click)

        self.start_btn = QPushButton()
        self.start_btn.setText('开启通知吧!')
        self.start_btn.clicked.connect(self.start_btn_click)

        self.stop_btn = QPushButton()
        self.stop_btn.setText('STOP')
        self.stop_btn.clicked.connect(self.stop_btn_click)

        form = QFormLayout()
        form.addRow(self.notify_subject_label, self.notify_subject_text)
        form.addRow(self.notify_current_label, self.notify_current_text)
        form.addRow(self.notify_time_label, self.notify_time_combox)
        form.addRow(self.notify_icon_path, self.notify_icon_btn)

        vbox = QVBoxLayout()
        vbox.addLayout(form)
        vbox.addWidget(self.start_btn)
        vbox.addWidget(self.stop_btn)

        self.thread_ = WorkThread(self)

        self.setLayout(vbox)

    def notify_icon_btn_click(self):
        file = QFileDialog.getOpenFileName(self, os.getcwd(), '打开图片', 'ICO File(*.ico)')
        print(file[0])
        self.notify_icon_path.setText(file[0])

    def start_btn_click(self):
        self.start_btn.setEnabled(False)
        self.thread_.start()

    def stop_btn_click(self):
        self.start_btn.setEnabled(True)
        QApplication.instance().quit()
        # self.thread_.quit()

    # 创建托盘图标
    def createTrayIcon(self):
        aRestore = QAction('恢复(&R)', self, triggered=self.show)
        aQuit = QAction('退出(&Q)', self, triggered=QApplication.instance().quit)
 
        menu = QMenu(self)
        menu.addAction(aRestore)
        menu.addAction(aQuit)
 
        self.trayIcon = QSystemTrayIcon(self)
        self.trayIcon.setIcon(QIcon('uuus.ico'))
        self.trayIcon.setContextMenu(menu)
        self.trayIcon.activated.connect(self.iconActivated)
 
 
    def iconActivated(self, reason):
        if reason in (QSystemTrayIcon.DoubleClick, QSystemTrayIcon.MiddleClick):
            self.show()
 
    def closeEvent(self, event):
        if self.trayIcon.isVisible():
            QMessageBox.information(self, '系统托盘',
                                    '程序将继续在系统托盘中运行，要终止本程序，\n'
                                    '请在系统托盘入口的上下文菜单中选择"退出"')
            self.hide()
            event.ignore()


class WorkThread(QThread):
    def __init__(self,parent=None):
        super(WorkThread, self).__init__(parent)
        self.parent = parent
        self.notify = ToastNotifier()
        self.working = True

    def __del__(self):
        self.working = False
        self.wait()

    def run(self):
        self.show_toast()

    def show_toast(self):
        notify_head = self.parent.notify_subject_text.text()
        notify_text = self.parent.notify_current_text.text()
        notify_ico = self.parent.notify_icon_path.text()
        notify_sen = self.parent.notify_time_combox.currentText().split('|')[0]
        notify_sen = int(notify_sen) #* 60
        print('当前时间:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
        self.notify.show_toast(f"{notify_head}", f"{notify_text}", duration=10, threaded=True, icon_path=notify_ico)
        while self.notify.notification_active():
            time.sleep(0.005)
        timer = Timer(notify_sen, self.show_toast)
        timer.start()




if __name__ == '__main__':
    app = QApplication(sys.argv)
    QApplication.setQuitOnLastWindowClosed(False)
    window = WinNotify()
    window.show()
    sys.exit(app.exec_())